package com.ftg.learn.util;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * When a request matches a route, the filtering web handler adds all instances of GlobalFilter and all route-specific instances of GatewayFilter to a filter chain. This combined filter chain is sorted by the org.springframework.core.Ordered interface, which you can set by implementing the getOrder() method.
 *
 * As Spring Cloud Gateway distinguishes between “pre” and “post” phases for filter logic execution (see How it Works), the filter with the highest precedence is the first in the “pre”-phase and the last in the “post”-phase.
 *
 * The following listing configures a filter chain:
 * 通过测试发现GlobalFilter 可以使用，并能成功拦截
 */
public class CrosConfig implements GlobalFilter, Ordered {

    /**
     * 重写方法
     * @param exchange  交互机
     * @param chain     过滤器放行
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("官网过滤");
        //获得服务器响应
        //web Request(请求) Response(响应) | 浏览器发现没有response header ACCESS_CONTROL_ALLOW_HEADERS ACCESS_CONTROL_ALLOW_METHODS ACCESS_CONTROL_ALLOW_ORIGIN

        //http response 响应
        ServerHttpResponse response = exchange.getResponse();

        //拿到服务器头部
        HttpHeaders headers = response.getHeaders();

        //添加响应头，完成对cros的配置
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS,"Origin,X-Requested-With,Content-Type,Accept");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS,"*");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN,"*");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true");

        return chain.filter(exchange);
    }

    /**
     * 表示当前filter 先走
     *  从小到大执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}